package com.example.demo.exception;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSException;
import com.example.demo.constant.Code;
import com.example.demo.pojo.Result;
import jakarta.validation.ValidationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    public Result handleException(BindException bindException) {
        bindException.printStackTrace();

        List<ObjectError> allErrors = bindException.getBindingResult().getAllErrors();

        String message = new String();

        for (ObjectError error:
             allErrors) {
            message += error.getDefaultMessage() + " ";
        }

        return new Result(Code.PATTERN_ERR, null, message);
    }

    @ExceptionHandler(ValidationException.class)
    public Result handleException(ValidationException validationException) {
        validationException.printStackTrace();

        return new Result(Code.PATTERN_ERR, null, validationException.getMessage());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result handleException(HttpMessageNotReadableException httpMessageNotReadableException) {
        httpMessageNotReadableException.printStackTrace();

        return new Result(Code.PATTERN_ERR, null, httpMessageNotReadableException.getMessage());
    }

    @ExceptionHandler(OSSException.class)
    public Result handleException(OSSException oe) {
        oe.printStackTrace();

        String message = "Caught an OSSException, which means your request made it to OSS, "
                + "but was rejected with an error response for some reason.\n"
                + "Error Message:" + oe.getErrorMessage() + "\n"
                + "Error Code:" + oe.getErrorCode() + "\n"
                + "Request ID:" + oe.getRequestId() + "\n"
                + "Host ID:" + oe.getHostId() + "\n";

        return new Result(Code.OSS_ERR, null, message);
    }

    @ExceptionHandler(ClientException.class)
    public Result handleException(ClientException ce) {
        ce.printStackTrace();

        String message = "Caught an ClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with OSS, "
                + "such as not being able to access the network.\n"
                + "Error Message:" + ce.getMessage() + "\n";

        return new Result(Code.OSS_ERR, null, message);
    }
}
